package cn.azy.document.tool;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ Author     ：AZY.
 * @ Date       ：Created in 10:08 2019/10/22
 * @ Description：${DESCRIPTION}
 */
@Slf4j
public class ReadWordThread {

    public static void word() throws Exception {
//        getWord();
        getTable();
    }

    public static void getWord(){
        String filePath = "F:\\安装包\\2018年降雨量统计表 - 1.doc";
        try{
            FileInputStream in = new FileInputStream(filePath);//载入文档
            WordExtractor ex = new WordExtractor(in);
            String s = ex.getText();
            System.out.println(s.indexOf("昌平区"));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void getTable() throws Exception{
        String filePath = "F:\\安装包\\2018年降雨量统计表 - 1.docx";
        FileInputStream in = new FileInputStream(filePath);//载入文档
        //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
        XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
        List<XWPFParagraph> paragraphs = xwpf.getParagraphs();
        List<String> name = new ArrayList<>();
        List<String> time = new ArrayList<>();
        Map<String , List<Map<String,String>>> excelMap = new HashMap<>();
        for(XWPFParagraph x : paragraphs){
            String s = x.getText();
            if(s.indexOf("昌平区")==0){
                List<Map<String,String>> l = new ArrayList<>();
                excelMap.put(s.substring(s.indexOf("昌平区")+3,s.indexOf("站降水量月报表")).trim(),l);
                name.add(s.substring(s.indexOf("昌平区")+3,s.indexOf("站降水量月报表")).trim());
            }else if(s.trim().length()==0){

            }else{
                s = s.replace("年","-");
                s = s.replace("月","-");
                time.add(s.trim());
            }
        }
        Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
        int num = 0;

        List<Map<String,String>> list = new CopyOnWriteArrayList<>();
        ExecutorService cachedThreadPoolin = Executors.newCachedThreadPool();
        while(it.hasNext()){

            cachedThreadPoolin.execute(new SaveDataToQueue(list, it.next(), name, time, num));
            num += 1;
        }
        cachedThreadPoolin.shutdown();
        while (true) {
            if (cachedThreadPoolin.isTerminated()) { // 计算耗时
                break;
            }
        }


        //写入一个文件
        exprotExcelAll(list);
        //分别写入各自文件
//        exprotExcel(excelMap,list);


    }

    public static void exprotExcel(Map<String,List<Map<String,String>>> excelMap,List<Map<String,String>> list){
        for(Map.Entry<String,List<Map<String,String>>> entry:excelMap.entrySet()){
            for(Map<String,String > m : list){
                if(m.get("name").equals(entry.getKey())){
                    entry.getValue().add(m);
                }
            }
            new Thread(new PutDataToFile(entry.getValue(),entry.getKey())).start();
        }
    }


    public static void exprotExcelAll(List<Map<String,String>> list){
        OutputStream out = null;
        try{
            String excelName = "F:\\昌平雨量1\\总.xlsx";
            // 读取Excel文档
            File finalXlsxFile = new File(excelName);
            if(!finalXlsxFile.isFile()){
                File file = new File("F:\\昌平雨量1\\1.xlsx");
                Files.copy(file.toPath(),finalXlsxFile.toPath());
            }
            FileInputStream finalXlsxFilein = new FileInputStream(finalXlsxFile);
            Workbook workBook = new XSSFWorkbook(finalXlsxFilein);
            Sheet sheet = workBook.getSheetAt(0);

            ExecutorService cachedThreadPoolout = Executors.newCachedThreadPool();
            //每个线程处理数据量
            int size = 500;
            for(int o = 1;o<=(list.size()/size)+1;o++){
                cachedThreadPoolout.execute(new PutDataToFileAll(list,o,size,sheet));
            }
            cachedThreadPoolout.shutdown();
            while (true) {
                if (cachedThreadPoolout.isTerminated()) { // 计算耗时
                    break;
                }
            }

            // 创建文件输出流，准备输出电子表格：这个必须有，否则你在sheet上做的任何操作都不会有效
            out = new FileOutputStream(excelName);
            log.info("开始写入"+excelName);
            workBook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if(out != null){
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断Excel的版本,获取Workbook
     * @param
     * @param
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbok(File file) throws IOException {
        Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if(file.getName().endsWith("xls")){     //Excel&nbsp;2003
            wb = new HSSFWorkbook(in);
        }else if(file.getName().endsWith("xlsx")){    // Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }

}
